package com.abocode.aichat.core.application;

import com.abocode.aichat.core.application.impl.UserValidateService;
import com.abocode.aichat.server.channel.ChannelWrapper;
import com.abocode.aichat.server.context.ServerRuntimeContext;
import com.abocode.aichat.server.entity.EntityImpl;
import com.abocode.aichat.server.modules.ModuleHandler;
import com.abocode.aichat.server.reply.Replies;
import com.abocode.aichat.server.stanza.Stanza;
import com.abocode.aichat.server.stanza.StanzaWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by franky.
 */
@Service("authHandler")
public class AuthHandler implements ModuleHandler {
    @Autowired
    private UserValidateService userValidateService;

    public Replies execute(ChannelWrapper channelWrapper, Stanza stanza, ServerRuntimeContext serverRuntimeContext) {
        if(userValidateService ==null){
            throw new RuntimeException("IUserValidate is not found");
        }
        Map body = stanza.body();
        boolean flag= userValidateService.validate(body);
        if (flag) {
            EntityImpl entity = userValidateService.entity(body);
            serverRuntimeContext.getProtocolChannelRegistry().registerEntity(channelWrapper.getChannel(), entity);
            Replies replies = new Replies();
            Map map = new HashMap();
            map.put("status", 200);
            map.put("jid", entity.getFullName());
            //todo jid return
            Stanza _stanza = StanzaWrapper.wrapper(stanza, map);
            replies.addReply(channelWrapper.getChannel(), _stanza);
            return replies;
        }else{
            throw new RuntimeException("validate error");
        }
    }

    public String module() {
        return "auth";
    }
}
